package com.shiguiwu.springmybatis.algorithm.stack;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * @description: 波兰表达式计算
 * @author: stone
 * @date: Created by 2022/11/19 18:56
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.algorithm.polang
 */
@Slf4j
public class PolandTests {

    public static void main(String[] args) {
        suffixExpression( "4 5 * 8 - 60 + 8 2 / +");
    }


    /**
     * 后缀表达式的计算
     * 也叫逆波兰表达式
     *
     * @param expression 表达式
     *                   <p>
     *                   "4 5 * 8 - 60 + 8 2 / +"
     */
    public static void suffixExpression(String expression) {
        Stack<String> stock = new Stack<>();
        String[] list = expression.split("\\s+");
        for (String item : list) {
            if (item.matches("\\d+")) {
                stock.push(item);
            } else {
                int y = Integer.parseInt(stock.pop());
                int x = Integer.parseInt(stock.pop());
                int result = calculate(x, y, item);
                stock.push(String.valueOf(result));
            }


        }

        log.info("计算结果为 ====> {}", stock.pop());



    }


    public static Integer calculate(int x, int y, String exp) {
        int result = 0;

        switch (exp) {
            case "+":
                result = x + y;
                break;
            case "-":
                result = x - y;
                break;
            case "*":
                result = x * y;
                break;
            case "/":
                result = x / y;
                break;
            default:
                throw new UnsupportedOperationException("不支持其他操作");

        }
        return result;

    }
}

